package com.lm.xstream.example;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SimpleExpressionEvaluator {
    public static void main(String[] args) {
        String expression = "200+300+200+200+200+200+200+200+200+300+300+200+200+200+200+200+200+200+300+200+200+200+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300-5000+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+300+600+200+100+300-5000";
        int result = evaluateWithRegex(expression);

        System.out.println("结果是: " + result);

        List<String> plusTerms = extractPlusTerms(expression);

        System.out.println("加号项：");
        for (String term : plusTerms) {
            System.out.println(term);
        }
    }

    public static List<String> extractPlusTerms(String expr) {
        List<String> result = new ArrayList<>();

        // 确保表达式每个数前都有符号
        if (expr.charAt(0) != '+' && expr.charAt(0) != '-') {
            expr = "+" + expr;
        }

        // 匹配 + 或 - 后面的数字
        Matcher matcher = Pattern.compile("([+-]\\d+)").matcher(expr);

        while (matcher.find()) {
            String term = matcher.group(1);
            if (term.startsWith("+")) {
                result.add(term);
            }
        }

        return result;
    }

    public static int evaluate(String expr) {
        int total = 0;
        int number = 0;
        char sign = '+'; // 初始符号为正号

        for (int i = 0; i < expr.length(); i++) {
            char c = expr.charAt(i);

            if (Character.isDigit(c)) {
                number = number * 10 + (c - '0');
            }

            // 如果遇到符号或到达末尾，就执行运算
            if (!Character.isDigit(c) || i == expr.length() - 1) {
                if (sign == '+') {
                    total += number;
                } else if (sign == '-') {
                    total -= number;
                }
                sign = c; // 更新下一个操作符
                number = 0;
            }
        }

        return total;
    }

    public static int evaluateWithRegex(String expr) {
        expr = expr.replaceAll(" ", "");
        if (expr.charAt(0) != '+' && expr.charAt(0) != '-') {
            expr = "+" + expr; // 确保第一个数带符号
        }

        int sum = 0;
        java.util.regex.Matcher m = java.util.regex.Pattern
                .compile("([+-])([0-9]+)")
                .matcher(expr);

        while (m.find()) {
            String sign = m.group(1);
            int num = Integer.parseInt(m.group(2));
            sum += sign.equals("+") ? num : -num;
        }
        return sum;
    }

}
